<template>
  <div class="search">
    <div class="totalCount">
        <p class="countTitle">合计</p>
        <div class="totalList">
          <p>
            充值钱包：<span>焕贝{{ allData.rechargeMoney }}</span>
          </p>
        </div>
      </div>
    <Card>
      <Row @keydown.enter.native="handleSearch">
        <Form ref="searchForm" :model="searchForm" inline :label-width="85" class="search-form">
          <Form-item label="到期时间">
            <DatePicker v-model="selectDate" type="datetimerange" format="yyyy-MM-dd" clearable
              @on-change="selectDateRange" placeholder="选择起始时间" style="width: 300px"></DatePicker>
          </Form-item>
          <Form-item label="联系方式" prop="mobile">
            <Input type="text" v-model="searchForm.mobile" placeholder="请输入会员联系方式" clearable style="width: 200px" />
          </Form-item>
          <Form-item label="区域" prop="name" v-show="userEnums == 'MANAGER'">
            <regionArea style="width: 350px" @selected="selectedRegions" :showIs="true" />
          </Form-item>
          <Form-item label="会员等级" prop="level">
            <Select v-model="searchForm.level" placeholder="请选择" clearable style="width: 200px">
              <Option value="0">普通会员</Option>
              <Option value="1">银卡会员</Option>
              <Option value="2">金卡会员</Option>
            </Select>
          </Form-item>
          <Form-item label="推广人姓名" prop="nameExte">
            <Input type="text" v-model="searchForm.nameExte" placeholder="请输入推广人姓名" clearable style="width: 200px" />
          </Form-item>
          <Form-item label="推广人手机号" prop="mobileExte">
            <Input type="text" v-model="searchForm.mobileExte" placeholder="请输入推广人手机号" clearable style="width: 200px" />
          </Form-item>
          <Button @click="handleSearch" class="search-btn" type="primary" icon="ios-search">搜索</Button>
          <download-excel class="export-excel-wrapper" :data="data" :fields="fields" :fetch="exportOrder" name="C端会员.xls">
            <Button type="info" class="export"> 导出 </Button>
          </download-excel>
        </Form>
      </Row>
      <Table :loading="loading" border :columns="columns" class="mt_10" :data="data" ref="table"></Table>
      <Row type="flex" justify="end" class="mt_10">
        <Page :current="searchForm.pageNumber" :total="total" :page-size="searchForm.pageSize" @on-change="changePage"
          @on-page-size-change="changePageSize" :page-size-opts="[10, 20, 50, 100]" size="small" show-total
          show-elevator show-sizer></Page>
      </Row>
    </Card>
    <!-- 添加用户模态框 -->
    <Modal v-model="addFlag" title="添加商家会员">
      <Form ref="addMemberForm" :model="addMemberForm" :rules="addRule" :label-width="100">
        <FormItem label="手机号码" prop="mobile" style="width: 90%">
          <Input v-model="addMemberForm.mobile" maxlength="11" placeholder="请输入手机号码" />
        </FormItem>
        <FormItem label="会员名称" prop="username" style="width: 90%">
          <Input v-model="addMemberForm.username" maxlength="15" placeholder="请输入会员名称" />
        </FormItem>
        <FormItem label="会员密码" prop="password" style="width: 90%">
          <Input type="password" password v-model="addMemberForm.password" maxlength="20" placeholder="请输入会员密码" />
        </FormItem>
        <Form-item label="会员类型" prop="type">
          <Select v-model="addMemberForm.type" style="width: 90%" placeholder="请选择用户类型" disabled>
            <Option v-for="item in typeList" :value="item.id" :key="item.id">{{
              item.label
            }}</Option>
          </Select>
        </Form-item>
      </Form>
      <div slot="footer">
        <Button @click="addFlag = false">取消</Button>
        <Button type="primary" @click="addMemberSubmit">确定</Button>
      </div>
    </Modal>
    <!-- 修改模态框 -->
    <Modal v-model="descFlag" :title="descTitle" @on-ok="handleSubmitModal" width="500">
      <Form ref="form" :model="form" :rules="ruleValidate" :label-width="80">
        <FormItem label="头像">
          <img :src="form.face" class="face" />
          <Button type="text" class="upload" @click="
              () => {
                this.picModelFlag = true;
                this.$refs.ossManage.selectImage = true;
              }
            ">修改</Button>
          <input type="file" style="display: none" id="file" />
        </FormItem>
        <FormItem label="用户名" prop="name">
          <Input v-model="form.username" style="width: 200px" disabled />
        </FormItem>
        <FormItem label="用户昵称" prop="name">
          <Input v-model="form.nickName" style="width: 200px" />
        </FormItem>
        <FormItem label="性别" prop="sex">
          <RadioGroup type="button" button-style="solid" v-model="form.sex">
            <Radio :label="1">
              <span>男</span>
            </Radio>
            <Radio :label="0">
              <span>女</span>
            </Radio>
          </RadioGroup>
        </FormItem>
        <FormItem v-if="typeid == 1" label="修改密码" prop="password">
          <Input type="password" style="width: 220px" password v-model="form.newPassword" />
        </FormItem>
        <FormItem label="生日" prop="birthday">
          <DatePicker type="date" format="yyyy-MM-dd" v-model="form.birthday" style="width: 220px">
          </DatePicker>
        </FormItem>
        <FormItem label="所在地" prop="mail">
          <div class="form-item" v-if="!updateRegion">
            <Input disabled style="width: 250px" :value="form.region" />
            <Button type="text" @click="
                () => {
                  this.updateRegion = !this.updateRegion;
                }
              ">修改</Button>
          </div>
          <div class="form-item" v-else>
            <region style="width: 250px" @selected="selectedRegion" />
          </div>
        </FormItem>
      </Form>
    </Modal>
    <Modal width="1200px" v-model="picModelFlag">
      <ossManage @callback="callbackSelected" ref="ossManage" />
    </Modal>
    <Modal width="500px" title="改区域" v-model="changeRegionModal" @on-ok="confirmChangeRegion"
      @on-cancel="cancelChangeRegion">
      <Form ref="form" :model="form" :label-width="120">
        <FormItem label="原区域">
          <div class="name">{{memberItem.locationName||''}}</div>
        </FormItem>
        <FormItem label="新区域">
          <regionevery v-if="memberItem.partnerType==4" ref="region" style="width: 250px" level="3"
            @selected="changeSelectRegion" />
          <region v-else ref="region" style="width: 250px" level="3" @selected="changeSelectRegion" />
        </FormItem>
      </Form>
    </Modal>
    <Modal width="500px" title="区域历史" footer-hide v-model="regionHistoryModal">
      <Table :loading="regionLoading" border :columns="regionColumns" class="mt_10" :data="regionData" ref="table">
      </Table>
    </Modal>
  </div>
</template>

<script>
  import region from "@/views/lili-components/region";
  import regionevery from "@/views/lili-components/region-every";
  import ossManage from "@/views/sys/oss-manage/ossManage";
  import regionArea from "@/views/agent-manage/region";
  import * as API_Member from "@/api/member.js";
  import * as RegExp from "@/libs/RegExp.js";
  import JsonExcel from "vue-json-excel";
  import {
    getStore,
    setStore
  } from "@/libs/storage.js";

  export default {
    name: "member",
    components: {
      region,
      regionevery,
      regionArea,
      ossManage,
      "download-excel": JsonExcel,
    },
    data() {
      return {
      // 表格的表头以及内容
      fields: {
        会员名称: "username",
        会员昵称: "nickName",
        联系方式: {
          field: "mobile",
          callback: (value) => {
            return "&nbsp;" + value
          },
        },
        会员等级: "gradeText",
        区域: {
          field: "locationName",
          callback: (value) => {
            return "&nbsp;" + value
          },
        },
        推广人姓名: 'nameExte',
        推广人手机号: 'mobileExte',
        注册时间: "createTime",
        到期时间: "memberEndTime",
        充值现金总额: "rechargeMoney",
      },
        userEnums: "", //角色
        descTitle: "", // modal标题
        descFlag: false, //编辑查看框
        loading: true, // 表单加载状态
        addFlag: false, // modal显隐控制
        updateRegion: false, // 地区
        selectDate: null, // 选择时间段
        addMemberForm: {
          // 添加用户表单
          mobile: "",
          username: "",
          password: "",
          regionId: "",
          type: 1,
        },
        searchForm: {
          // 请求参数
          pageNumber: 1,
          pageSize: 10,
          order: "desc",
          username: "",
          mobile: "", //联系方式
          disabled: "OPEN",
          type: "2", //用户类型
          region: "",
          regionId: "", //区域
          beginTime: "", //下单使劲按
          endTime: "",
          level: "", //会员等级
          nameExte:'',
          mobileExte:'',
        },
        picModelFlag: false, // 选择图片
        form: {}, // 表单数据

        addRule: {
          // 验证规则
          mobile: [{
              required: true,
              message: "请输入手机号码",
            },
            {
              pattern: RegExp.mobile,
              message: "请输入正确的手机号",
            },
          ],
          username: [{
            required: true,
            message: "请输入会员名称",
          }, ],
          password: [{
            required: true,
            message: "请输入密码",
          }, ],
          // type: [{ required: true, message: "请选择用户类型", trigger: 'change' }],
        },
        ruleValidate: {}, //修改验证
        columns: [{
            title: "会员名称",
            key: "username",
            width: "150",
            tooltip: true,
          },
          {
            title: "会员昵称",
            key: "nickName",
            width: "150",
            tooltip: true,
          },
          {
            title: "区域",
            key: "locationName",
            width: "300",
            tooltip: true,
          },
         {
          title: "推广人姓名",
          key: "nameExte",
          width: "160",
          tooltip: true,
        },
        {
          title: "推广人手机号",
          key: "mobileExte",
          width: "140",
          tooltip: true,
        },
          {
            title: "联系方式",
            key: "mobile",
            width: "150",
            render: (h, params) => {
              if (params.row.mobile == null) {
                return h("div", [h("span", {}, "")]);
              } else {
                return h("div", [h("span", {}, params.row.mobile)]);
              }
            },
          },
          {
            title: "会员等级",
            key: "gradeText",
            width: "150",
          },
          {
            title: "注册时间",
            key: "createTime",
            width: "250",
          },
          {
            title: "到期时间",
            key: "memberEndTime",
            width: "250",
          },

          {
            title: "充值钱包余额",
            key: "rechargeMoney",
            width: "150",
            render: (h, params) => {
              if (params.row.rechargeMoney == null) {
                return h("div", [h("span", {}, "")]);
              } else {
                return h("div", [
                  h("span", {}, "焕贝" + params.row.rechargeMoney),
                ]);
              }
            },
          },
          // {
          //   title: "推广钱包余额",
          //   key: "promoteMoney",
          //   width: "150",
          //   render: (h, params) => {
          //     if (params.row.promoteMoney == null) {
          //       return h("div", [h("span", {}, "")]);
          //     } else {
          //       return h("div", [
          //         h("span", {}, "焕贝" + params.row.promoteMoney),
          //       ]);
          //     }
          //   },
          // },
          {
            title: "操作",
            key: "action",
            align: "center",
            width: 300,
            fixed: "right",
            render: (h, params) => {
              return h(
                "div", {
                  style: {
                    display: "flex",
                    justifyContent: "center",
                  },
                },
                [
                  h(
                    "Button", {
                      props: {
                        size: "small",
                        type: params.row.___selected ? "primary" : "default",
                      },
                      style: {
                        marginRight: "5px",
                        display: this.selectedMember ? "block" : "none",
                      },
                      on: {
                        click: () => {
                          this.callback(params.row, params.index);
                        },
                      },
                    },
                    params.row.___selected ? "已选择" : "选择"
                  ),
                  h(
                    "Button", {
                      props: {
                        type: "info",
                        size: "small",
                      },
                      style: {
                        marginRight: "5px",
                        display: this.selectedMember ? "none" : "block",
                      },
                      on: {
                        click: () => {
                          this.changeRegion(params.row);
                        },
                      },
                    },
                    "改区域"
                  ),
                  h(
                    "Button", {
                      props: {
                        type: "info",
                        size: "small",
                      },
                      style: {
                        marginRight: "5px",
                        display: this.selectedMember ? "none" : "block",
                      },
                      on: {
                        click: () => {
                          this.regionHistory(params.row);
                        },
                      },
                    },
                    "区域记录"
                  ),
                  h(
                    "Button", {
                      props: {
                        type: "success",
                        size: "small",
                      },
                      style: {
                        marginRight: "5px",
                        display: this.selectedMember ? "none" : "block",
                      },
                      on: {
                        click: () => {
                          this.detail(params.row);
                        },
                      },
                    },
                    "查看"
                  ),
                  h(
                    "Button", {
                      props: {
                        size: "small",
                        type: "error",
                      },
                      style: {
                        marginRight: "5px",
                        display: this.selectedMember ? "none" : "block",
                      },
                      on: {
                        click: () => {
                          this.disabled(params.row);
                        },
                      },
                    },
                    "禁用"
                  ),
                ]
              );
            },
          },
        ],
        data: [], // 表单数据
        total: 0, // 表单数据总数
        selectMember: [], //保存选中的用户
        // 会员类型下拉框
        typeList: [{
            id: 0,
            label: "全部",
          },
          {
            id: 1,
            label: "商家用户",
          },
          {
            id: 2,
            label: "小程序用户",
          },
        ],
        allData: {}, //获取列表总总额的数据
        typeid: "",
        // 修改地区弹窗 --start--
        changeRegionModal: false, // 修改区域弹窗
        memberItem: {},
        regionHistoryModal: false, // 地区历史弹窗
        regionLoading: true, // 表单加载状态
        regionColumns: [{
          title: "原地区",
          key: "beforeName",
          width: "150",
          tooltip: true,
        }, {
          title: "新地区",
          key: "afterName",
          width: "150",
          tooltip: true,
        }, {
          title: "变更时间",
          key: "createTime",
          width: "150",
          tooltip: true,
        }, ],
        regionData: []
        // 修改地区弹窗 --end--
      };
    },
    props: {
      // 是否为选中模式
      selectedMember: {
        type: Boolean,
        default: false,
      },
      // 已选择用户数据
      selectedList: {
        type: null,
        default: () => {
          return [];
        },
      },
    },
    watch: {
      selectedList: {
        handler(val) {
          this.$set(this, "selectMember", JSON.parse(JSON.stringify(val)));
          this.init(this.data);
          // 将父级数据与当前组件数据进行匹配
        },
        deep: true,
        immediate: true,
      },
    },
    methods: {
       // 导出订单
     async exportOrder () {
       if (this.searchForm.regionId) {
         this.searchForm.regionId = this.searchForm.regionId.toString()
       }
 
       const params = JSON.parse(JSON.stringify(this.searchForm))
       params.pageNumber = 1
       params.pageSize = 999999999
       const result = await API_Member.getCMemberList(params)
       if (result.success) {
         if (result.result.records.length === 0) {
           this.$Message.warning("暂无可导出数据")
           return []
         } else {
           return result.result.records
         }
       } else {
         this.$Message.warning("导出数据失败，请重试")
       }
     },
      selectDateRange(v) {
        if (v) {
          this.searchForm.beginTime = v[0];
          this.searchForm.endTime = v[1];
        }
      },
      // 选中的地址
      selectedRegions(val) {
        this.searchForm.regionId = val[0];
      },
      // 回调给父级
      callback(val, index) {
        this.$set(val, "___selected", !val.___selected);
        console.log(val.___selected);
        console.log(this.selectMember);
        let findUser = this.selectMember.find((item) => {
          return item.id == val.id;
        });
        // 如果没有则添加
        if (!findUser) {
          this.selectMember.push(val);
        } else {
          // 有重复数据就删除
          this.selectMember.map((item, index) => {
            if (item.id == findUser.id) {
              this.selectMember.splice(index, 1);
            }
          });
        }

        this.$emit("callback", val);
      },
      // 初始化信息
      init(data) {
        data.forEach((item) => {
          if (this.selectMember.length != 0) {
            this.selectMember.forEach((member) => {
              if (member.id == item.id) {
                this.$set(item, "___selected", true);
              }
            });
          } else {
            this.$set(item, "___selected", false);
          }
        });
        this.data = data;
      },
      // 分页 改变页码
      changePage(v) {
        this.searchForm.pageNumber = v;
        this.getData();
      },
      // 分页 改变页数
      changePageSize(v) {
        this.searchForm.pageSize = v;
        this.searchForm.pageNumber = 1;
        this.getData();
      },
      // 搜索
      handleSearch() {
        this.searchForm.pageNumber = 1;
        this.searchForm.pageSize = 10;
        this.getData();
      },
      //查看详情修改
      editPerm(val) {
        this.descTitle = `查看用户 ${val.username}`;
        this.descFlag = true;
        this.typeid = val.type;
        this.updateRegion = false;
        this.getMemberInfo(val.id);
      },
      addMember() {
        this.addFlag = true;
        this.$refs.addMemberForm.resetFields();
      },
      /**
       * 查询查看会员详情
       */
      getMemberInfo(id) {
        API_Member.getMemberInfoData(id).then((res) => {
          if (res.result) {
            this.$set(this, "form", res.result);
          }
        });
      },

      //查询会员列表
      getData() {
        this.loading = true;
        if (this.searchForm.regionId) {
          this.searchForm.regionId = this.searchForm.regionId.toString();
        }

        API_Member.getCMemberList(this.searchForm).then((res) => {
          if (res.result.records) {
            this.loading = false;
            this.init(res.result.records);
            this.total = res.result.total;
          }
        });
       API_Member.MemberListAll(this.searchForm).then((res) => {
        if (res.code == 200) {
          this.allData = res.result
        }
      })
      },
      // 选中的图片
      callbackSelected(val) {
        this.picModelFlag = false;
        this.form.face = val.url;
      },
      //添加会员提交
      addMemberSubmit() {
        this.addMemberForm.password = this.md5(this.addMemberForm.password);
        this.$refs.addMemberForm.validate((valid) => {
          if (valid) {
            API_Member.addMember(this.addMemberForm).then((res) => {
              if (res.result) {
                this.$refs.addMemberForm.resetFields();
                this.getData();
                this.$Message.success("添加成功！");
                this.addFlag = false;
              }
            });
          } else {
            this.$Message.error("必填项不能为空！");
          }
        });
      },

      // 选中的地址
      selectedRegion(val) {
        this.region = val[1];
        this.regionId = val[0];
      },
      // 选中的地址
      selectedRegionSearch(val) {
        this.searchForm.region = val[1];
        this.searchForm.regionId = val[0];
      },
      //查看会员
      detail(row) {
        this.$router.push({
          name: "member-detail",
          query: {
            id: row.id,
          },
        });
      },

      //禁用会员
      disabled(v) {
        let params = {
          memberIds: [v.id],
          disabled: false,
        };
        this.$Modal.confirm({
          title: "提示",
          content: "<p>确认禁用此会员？</p>",
          onOk: () => {
            API_Member.updateMemberStatus(params).then((res) => {
              if (res.success) {
                this.$Message.success("禁用成功");
                this.getData();
              } else {
                // this.$Message.error(res.message);
              }
            });
          },
        });
      },

      // 提交修改数据
      handleSubmitModal() {
        const {
          nickName,
          sex,
          username,
          face,
          newPassword
        } = this.form;
        let time = new Date(this.form.birthday);
        let birthday =
          time.getFullYear() + "-" + (time.getMonth() + 1) + "-" + time.getDate();
        let submit = {
          regionId: this.form.regionId,
          region: this.form.region,
          nickName,
          username,
          sex,
          birthday,
          face,
        };
        if (this.region != "undefined") {
          submit.regionId = this.regionId;
          submit.region = this.region;
        }
        if (newPassword) {
          submit.password = this.md5(newPassword);
        }
        API_Member.updateMember(submit).then((res) => {
          if (res.code == 200) {
            this.$Message.success("修改成功！");
            this.getData();
          } else {
            this.$Message.error("修改失败！");
          }
        });
      },
      // 修改地区弹窗 --start--
      changeRegion(row) {
        this.changeRegionModal = true;
        this.$refs.region.addr = []
        this.memberItem = {
          id: row.id,
          locationName: row.locationName,
          partnerType: row.partnerType
        }
      },
      // 选中的地址
      changeSelectRegion(val) {
        this.memberItem.region = val[0].join(',');
      },
      confirmChangeRegion() {
        if (!this.memberItem.region) return;
        API_Member.updateMemberRegion(this.memberItem).then((res) => {
          if (res.success) {
            this.getData()
          }
        })
      },
      cancelChangeRegion() {
        this.memberItem = {}
        this.$refs.region.addr = []
      },
      regionHistory(row) {
        this.regionLoading = true
        this.regionData = []
        this.regionHistoryModal = true;
        API_Member.updateMemberRegionHistory({
          id: row.id
        }).then((res) => {
          console.log(res)
          this.regionLoading = false
          this.regionData = res.result.records
        })
      },
      // 修改地区弹窗 --end--
    },
    mounted() {
      this.getData();
      this.userEnums = this.getStore("userEnums");
    },
  };
</script>
<style lang="scss" scoped>
  /deep/ .ivu-table-wrapper {
    width: 100%;
  }

  /deep/ .ivu-card {
    width: 100%;
  }

  .face {
    width: 60px;
    height: 60px;
    border-radius: 50%;
  }
  .totalCount {
  width: 100%;
  height: auto;
  .countTitle {
    width: 100%;
    height: auto;
    font-weight: bold;
    font-size: 24px;
  }
  .totalList {
    display: flex;
    align-items: center;
    p {
      margin-right: 20px;
      font-size: 18px;
      span {
        margin-left: 10px;
      }
    }
  }
}
.export-excel-wrapper {
  margin-left: 10px;
}
</style>
